import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-12
 * Time: 19:28
 */
class Student{
    public int classId;
    public int studentId;
}
@WebServlet("/studentInfo")
public class StudentInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //拿到query string
        String queryString = req.getQueryString();
        String classId = req.getParameter("classId");
        String studentId = req.getParameter("studentId");
        System.out.println("classId : " + classId + " studentId : " + studentId);
        resp.getWriter().write("classId : " + classId + " studentId : " + studentId);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //从请求的body中进行读取并进行解析
        //ObjectMapper 这个类是jackson的库中提供的类,可以帮助我们解析JSON格式的请求
        ObjectMapper objectMapper = new ObjectMapper();
        //代用readValue方法就可以将JSON格式的字符串转化成java对象-->然后通过java对象的属性就可以将其value值获取到
        //第一个参数是 获取流对象-->这样就可以从body中读取JSON格式的数据
        //第二个参数是 类对象--->转换的结果对应的java对象
        Student student = objectMapper.readValue(req.getInputStream(),Student.class);
        System.out.println("classId : " + student.classId + " studentId : " + student.studentId);
        resp.getWriter().write("classId : " + student.classId + " studentId : " + student.studentId);
    }
}
